<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <title>index</title>
  <link rel="stylesheet" href="layui-v2.5.5/css/layui.css">
</head>
<style type="text/css">
  #time_tool { position:absolute; left:10px; top:10px; background:#FFFFFF; width:100%;}
</style>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
  <div class="layui-header">
    <div class="layui-logo"></div>
    <!-- 头部区域（可配合layui已有的水平导航） -->
    <!-- 顶部部导航栏左侧start -->
    <ul class="layui-nav layui-layout-left">
      <li class="layui-nav-item" ><a href="index.html"><i class="layui-icon layui-icon-location"></i> 实时监控</a></li>
<!--       <li class="layui-nav-item" ><a href="trail.html"><i class="layui-icon layui-icon-engine"></i> 活动轨迹</a></li> -->
    </ul>
    <!-- 顶部部导航栏左侧end -->

    <!-- 顶部部导航栏右侧start -->
    <ul class="layui-nav layui-layout-right">
      <li class="layui-nav-item"><a href="/">退出</a></li>
    </ul>
  </div>

  <!-- 顶部部导航栏右侧end -->

  <!-- 侧边栏内容start -->
  <div class="layui-side">
    <div class="layui-coutainer">
     <form class="layui-form layui-form-pane" action="" style="width:auto;height: 20px;padding: 2px">
          <div class="layui-form-item">
              <div class="layui-inline">
                  <div class="layui-input-inline">
                      <input type="text" lay-verify="required" name="search_key" lay-reqtext="请输入搜索内容" placeholder="设备ID" autocomplete="off" class="layui-input" style="width:auto;height: 30px">
                  </div>
                  <div class="layui-inline" >
                      <a type="button" class="layui-btn layui-btn-sm" lay-submit="" lay-filter="dev-search-btn" >搜索</a>
                  </div>
              </div>
          </div>
      </form>
      <div class="" id="dev_list_panle">
        <div class="layui-card-body" style="padding: 2px;border: 1px">
          <table id="dev_list_show" lay-filter="dev_list_show"></table>
        </div>
      </div>
    </div>
  </div>
  <!-- 侧边栏内容end -->
  
  <!-- 内容主体区域sart -->

  <div class="layui-body" style="bottom: 0">
    <div id="map_box" class ="baidu-maps" style="width: 100%;height: 100%"></div>
    <div id="time_tool" style="color:white;background-color:rgba(320,138,138,0)">
      <form class="layui-form layui-form-pane " action="" id="trail_query_form" lay-filter="trail_query_form">
        <div class="layui-form-item" style="color:black">
          <div class="layui-inline">
            <div class="layui-input-inline">
              <input id="s_time" type="text" name="s_time" lay-verify="required"  placeholder="开始时间" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline">
              <input id="e_time" type="text" name="e_time" lay-verify="required"  placeholder="结束时间" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <div class="layui-input-inline" style="width: 150px">
              <select id="tml_list" name="device_id"  lay-verify="required" lay-search="" class="layui-input" placeholder="" >
              </select>
            </div>
            <div class="layui-form-mid layui-word-aux">—</div>
            <a class="layui-btn" lay-submit="" lay-filter="trail_query"><i class="layui-icon layui-icon-search" style="font-size: 12px"></i>轨迹查询</a>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- 内容主体区域end -->
  <div class="layui-footer" style="display: none;"></div>
</div>


<!-- 引用layui模块 -->
<script type="text/javascript" src="layui-v2.5.5/layui.all.js"></script>
<!-- 百度地图api调用，需要申请key，填入ak=后面 -->
<script type="text/javascript" src="http://api.map.baidu.com/getscript?v=2.0&ak="></script> 

<script type="text/javascript">

var $=layui.jquery;
var table=layui.table;
var laydate=layui.laydate;
var form=layui.form;


// 获取数据
var get_info_ajax=function(url,handle_kind='get_init_data',show_func=''){
  $.ajax({
    type: 'GET',
    url:url+"/?what="+handle_kind,
    async:true,
    dataType: 'json',
    // contentType:'application/json;charset=UTF-8',
    success: function(res) {
      console.log(res)
      if(show_func!=''){
        show_func(res)
      }
    },
    error:function(xhr,status,error){
      console.log(error)
      console.log(xhr)
      console.log(status)
    }
  });
}

// 后台数据交互
var post_info_ajax=function(base_info,url,handle_kind,show_func='',hanlde_page='colse_all'){
 
  base_info=JSON.stringify(base_info);
  // console.log(base_info)
  $.ajax({
    type: 'POST',
    data:base_info,
    url:url+"/index/?what="+handle_kind,
    async:true,
    dataType: 'json',
    success: function(res) {
      console.log('success',res)
      if(show_func!=''){
        show_func(res)
      }
      
    },
    error:function(xhr,status,error){
      console.log(error)
      console.log(xhr)
      console.log(status)
    }
  })
}
// post_data={'data':'post_ajax'}
// post_info_ajax(post_data,'http://127.0.0.1:8000','test')

// 设备列表数据加载函数
var device_list_table=function(table_data){
  // device=table_data
  table.render({
    elem: '#dev_list_show',
    data: table_data,
    id:'device_list',
    skin:'nob',
    size:'sm',
    height: 'full-330',
    cols: [[
        {type: "checkbox", fixed: "left"},
        {field: 'device_id', title: '设备ID',sort:true},
    ]],
    // page: true,
    limit:10000000
  });

  fill_option(table_data,'tml_list','device_id') 
  form.render() 
}

var dev_marker={}
table.on('row(dev_list_show)', function(obj){
  // console.log(obj)
  var dev=obj.data
  if(dev.lng && dev_marker[dev.device_id]==null){
    point=new BMap.Point(dev.lng,dev.lat)
    get_bdmap_addr(point,dev.device_id,dev)
    var marker = new BMap.Marker(point);
    var mylabel=new BMap.Label(dev.device_id,{offset:new BMap.Size(-3,-25)});
    marker.setLabel(mylabel);
    map.addOverlay(marker)
    map.centerAndZoom(point, 16);
    dev_marker[dev.device_id]=marker
    marker.detail=dev
    marker.addEventListener('click', function (e) {
      open_infowindow(e.target.detail)
    })
  }else{
    map.removeOverlay(dev_marker[dev.device_id])
    delete dev_marker[dev.device_id]
  }
});

get_info_ajax('http://127.0.0.1:8000','get_init_data',device_list_table)

//添加地图类型控件
var map = new BMap.Map("map_box");    // 创建Map实例
map.centerAndZoom(new BMap.Point(116.404, 39.915), 15);  // 初始化地图,设置中心点坐标和地图级别

map.addControl(new BMap.MapTypeControl({
  mapTypes:[
          BMAP_NORMAL_MAP,
          BMAP_HYBRID_MAP
      ]}));   
// map.setCurrentCity("北京");          // 设置地图显示的城市 此项是必须设置的
map.enableScrollWheelZoom(true);
map.enableAutoResize();
var geoc = new BMap.Geocoder();  //地理位置逆解析

var open_infowindow=function(data){

  var d=data.dynamic
  var loca=all_addr_obj[d.device_id]
  var content='<p>设备号：'+d.device_id+'</p>'+
              '<p>里程：'+d.mileage+'</p>'+
              '<p>速度：'+d.speed+'</p>'+
              '<p>位置：'+loca+'</p>'
  var opts = {
    width : 100,     // 信息窗口宽度
    // height: 280,     // 信息窗口高度
    offset:new BMap.Size(0, -32)
  };

  var infoWindow = new BMap.InfoWindow(content,opts,{anchor : new BMap.Size(20, 42)});
  map.openInfoWindow(infoWindow,point);
}

// 地址逆解析，从经纬度变成文字地址，百度接口
var all_addr_obj={};
var get_bdmap_addr=function(pt,key_field,dev){
  var location
  geoc.getLocation(pt, function(rs){
    var addComp = rs.address
    if(rs.surroundingPois.length!=0){
      // console.log(rs)
       location=addComp+','+rs.surroundingPois[0]['title'] 
    }else{
       location=addComp
    }
    all_addr_obj[key_field]=location;
    open_infowindow(dev)
  });
};

// 时间框
laydate.render({
  elem: '#s_time'
  ,type: 'datetime'
  ,value:new Date(new Date(new Date().toLocaleDateString()).getTime())
  ,btns: ['clear','now', 'confirm']
});

laydate.render({
  elem: '#e_time'
  ,type: 'datetime'
  ,value:new Date()
  ,btns: ['clear','now', 'confirm']
});

// 填充信息
var fill_option=function(fill_data,list_id,key,title=''){
  $('#'+list_id).empty()
  if(title==''){
    for (var i = fill_data.length - 1; i >= 0; i--) {
      var option='<option>'+fill_data[i][key]+'</option>'
      $('#'+list_id).append(option)
    }
  }else{
    for (var i = fill_data.length - 1; i >= 0; i--) {
      var option='<option value="'+fill_data[i][key]+'">'+fill_data[i][title]+'</option>'
      $('#'+list_id).append(option)
    }
  }
}

form.on('submit(trail_query)',function(obj){
  var trail_param=obj.field
  console.log(trail_param)
  post_info_ajax(trail_param,'http://127.0.0.1:8000','get_trail',handle_trail)
});

var handle_trail=function(pts){

  var tarckpoint=new Array();
  if(pts.length==0){
    layer.msg('该时间段没有轨迹数据');
    return false;
  };
  // 清除之前的覆盖物
  map.clearOverlays()
  //轨迹点封装
  
  for(var i=0;i<pts.length;i++){
    var lng=pts[i]['lng']
    var lat=pts[i]['lat']
    var pt_trail = new BMap.Point(lng,lat);
    tarckpoint.push(pt_trail);
  };
  var s_point=new BMap.Point(tarckpoint[0].lng,tarckpoint[0].lat);
  var e_point=new BMap.Point(tarckpoint[tarckpoint.length-1].lng,tarckpoint[tarckpoint.length-1].lat);
  var s_marker = new BMap.Marker(s_point);
  var e_marker=new BMap.Marker(e_point);
  var s_label=new BMap.Label('start',{offset:new BMap.Size(-3,-25)});
  var e_label=new BMap.Label('end',{offset:new BMap.Size(-3,-25)});
  s_marker.setLabel(s_label);
  e_marker.setLabel(e_label);
  map.addOverlay(s_marker); 
  map.addOverlay(e_marker); 
  var polyline = new BMap.Polyline(tarckpoint, {
      strokeColor:"#18a45b",//设置颜色
      strokeWeight:8 ,//宽度
      strokeOpacity:0.8,//折线的透明度，取值范围0 - 1
      enableEditing: false,//是否启用线编辑，默认为false
      enableClicking: false,//是否响应点击事件，默认为true
      // icons:[icons]
  });
  map.addOverlay(polyline);
  map.setViewport(tarckpoint);
}

</script>
</body>
</html>
